package com.scsj.supermarket.view.activity.serchmodel;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.HistoryAdapter;
import com.scsj.supermarket.adapter.HotAdapter;
import com.scsj.supermarket.base.SearchBase;
import com.scsj.supermarket.bean.SearchResultBean;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.presenter.SearchResultPresenter;
import com.scsj.supermarket.utils.AAMyAlertDialog;
import com.scsj.supermarket.utils.BaiduMapHelper;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.utils.SearchHistoryUtils;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * 搜索列表
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener {
//    private SearchResultPresenter searchResultPresenter;
    private EditText search_auto_tv;
    private HistoryAdapter newHistoryAdapter;
    private RecyclerView serch_hotsolo_rv;
    private HotAdapter hotAdapter;
    private List<String> data;
    private RecyclerView history_rv;
    private List<String> dataHis;
    private SimpleDateFormat mFormat;
    public static final String TAG = "SearchActivity";
    private ImageView deleteHistotyIv;
    private LinearLayout searchForResult;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_serch);
        initView();
        initListener();
        initData();
    }

    @Override
    protected void initView() {
//        searchResultPresenter = new SearchResultPresenter(this);
        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent firstEvent) {
                        if (firstEvent.getCode().equals("SearchCode1")) ;//内容对象创建接收
                        search_auto_tv.setText(firstEvent.getTitle());
                    }
                });

        deleteHistotyIv = findViewById(R.id.search_history_delete_iv);
        searchForResult = findViewById(R.id.search_for_result_ll);
        mFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        data = new ArrayList<>();
        data.add("小米手机");
        data.add("图书100-200");
        data.add("宝宝裙子");
        data.add("小牛电动车");
        data.add("华为手机");
        data.add("金利来");

        serch_hotsolo_rv = findViewById(R.id.serch_hotsolo_rv);
        serch_hotsolo_rv.setLayoutManager(new GridLayoutManager(this, 3));
        serch_hotsolo_rv.setNestedScrollingEnabled(false);
        hotAdapter = new HotAdapter(data);
        serch_hotsolo_rv.setAdapter(hotAdapter);
        dataHis = new ArrayList<>();

        dataHis.add("小米手机天蓝色最新款");
        dataHis.add("图书100-200");
        dataHis.add("宝宝裙子");
        dataHis.add("小牛电动车");
        dataHis.add("华为手机");
        dataHis.add("金利来");
        dataHis.add("农夫山泉矿泉水");

        history_rv = findViewById(R.id.history_rv);
        history_rv.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        history_rv.setNestedScrollingEnabled(false);

        newHistoryAdapter = new HistoryAdapter(dataHis);
        history_rv.setAdapter(newHistoryAdapter);
        search_auto_tv = findViewById(R.id.search_at);
    }

    @Override
    protected void initListener() {
        deleteHistotyIv.setOnClickListener(this);
        searchForResult.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    /**
     * 最多显示几条历史记录
     */
    private static final int HISTORY_MAX = 5;

    /**
     * 从SP查询搜索历史，并按时间显示
     */
    private void showSearchHistory() {
        Map<String, String> hisAll = (Map<String, String>) SearchHistoryUtils.getAll(this);
        //将key排序升序
        Object[] keys = hisAll.keySet().toArray();
        Arrays.sort(keys);
        int keyLeng = keys.length;
        //这里计算 如果历史记录条数是大于 可以显示的最大条数，则用最大条数做循环条件，防止历史记录条数-最大条数为负值，数组越界
        int hisLeng = keyLeng > HISTORY_MAX ? HISTORY_MAX : keyLeng;

        //为RecyclerView添加HeaderView和FooterView
        if (keyLeng == 0) {
            history_rv.setVisibility(View.GONE);
        } else {
            for (int i = 1; i <= keyLeng; i++) {
                dataHis.add(hisAll.get(keys[keyLeng - i]));
            }
            history_rv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 清楚历史记录
     */
    private void clearsearchHistory() {
        SearchHistoryUtils.clear(this);
        //同时刷新历史记录显示页面
        showSearchHistory();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_history_delete_iv:

                final AAMyAlertDialog alertDialog = new AAMyAlertDialog(this);
                alertDialog.setMessage("温馨提示");
                alertDialog.setMessageRed("您确认要删除最近搜索记录吗？");

                alertDialog.setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            clearsearchHistory();
                            alertDialog.dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                alertDialog.setNegativeButton("忽略", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            alertDialog.dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                alertDialog.show();

                break;
            case R.id.search_for_result_ll:
                final String searchText = search_auto_tv.getText().toString().trim();
                if (TextUtils.isEmpty(searchText)) {
                    Toasty.info(SearchActivity.this, "搜索内容不能为空").show();
                    return;
                }
//                Toasty.info(SearchActivity.this, "点击事件执行").show();
                SkipUtils.toSearchResultPage(this, searchText);

//                BaiduMapHelper
//                        .getInstance()
//                        .init(null)
//                        .params(SearchActivity.this)
//                        .showLocation();
//
//                RxBus.getDefault().toObservable(FirstEvent.class)
//                        //在io线程进行订阅，可以执行一些耗时操作
//                        .subscribeOn(Schedulers.io())
//                        //在主线程进行观察，可做UI更新操作
//                        .observeOn(AndroidSchedulers.mainThread())
//                        //观察的对象
//                        .subscribe(new Action1<FirstEvent>() {
//                            @Override
//                            public void call(FirstEvent firstEvent) {
//                                if (firstEvent.getCode().equals("location")) {
//                                    JSONObject jsonObject = new JSONObject();
//                                    jsonObject.put("latitude", firstEvent.getLatitude());
//                                    jsonObject.put("longitude", firstEvent.getLongitude());
//                                    jsonObject.put("searchName", searchText);
//                                    jsonObject.put("sortingType", 1);
//                                    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
//                                    searchResultPresenter.deliverData(body);
//                                }
//                            }
//                        });
                break;
            default:
                break;
        }
    }

//    @Override
//    public void showSuccessMsg(String s, SearchResultBean searchResultBean) {
//
//        Logger.e("数据获取成功，开始传递数据");
//        //获取成功，传递数据
////        if (searchResultBean.isSuccess()) {
////            SkipUtils.toSearchResultPage(this, searchResultBean);
////        }
//    }
//
//    @Override
//    public void showErrorMsg(String s) {
//
//    }
}
